#! /bin/env python
# -*- coding: utf-8 -*-
#
# $Id$

import sqlite3.dbapi2 as sqlite
import base64
import os
from mylog import *

class Settings:
	def __init__(self):
		db = os.path.expanduser("~/.fotoalba.db")
		self.db = db
		self.con = False
		self.cur = False
	
	def connect(self):
		log(u"Připojuji se k souboru s nastavením (%s)" %(self.db), 0)
		self.con = sqlite.connect(self.db)
		self.cur = self.con.cursor()

	def disconnect(self):
		self.con.close()

	def autologin(self):
		query = "SELECT nick, password FROM autologin WHERE 1=1	LIMIT 1"
		
		try:
			self.cur.execute(query)
		except sqlite.OperationalError:
			query = "CREATE TABLE autologin(nick TEXT, password TEXT)"
			log(u"Vytvářím tabulku pro autologin.", 0)
			self.cur.execute(query)
			return False
		except:
			raise
		
		result = self.cur.fetchone()
		if result == None:
			return False
		return [result[0], base64.decodestring(result[1])]
	
	def clearLogin(self):
		log(u"Promazávám nastavení.", 0)
		query = "DELETE FROM autologin WHERE 1=1"
		self.cur.execute(query)

	
	def saveLogin(self, nick, passwd):
		self.clearLogin()

		log(u"Ukládám nastavení.", 0)
		query = "INSERT INTO autologin(nick, password) VALUES ('%s','%s')" %(nick, base64.encodestring(passwd))
		self.cur.execute(query)
		self.con.commit()
